#!/usr/bin/env bash

# set -euox pipefail
DIR="$( cd "$(dirname "$0")" ; pwd -P )"
cd ${DIR}

#TARGET="ubuntu@172.30.18.237" PORT="8888" GATEWAY="ubuntu@13.251.73.175" bash -c 'ssh -tt -AL ${PORT}:localhost:${PORT} ${GATEWAY} "ssh -AL ${PORT}:localhost:${PORT} ${TARGET}"'
#TARGET="ubuntu@192.168.9.160" PORT="8888" GATEWAY="ubuntu@52.77.252.136" bash -c 'ssh -tt -AL ${PORT}:localhost:${PORT} ${GATEWAY} "ssh -AL ${PORT}:localhost:${PORT} ${TARGET}"'
#curl -sSL -X POST http://localhost:8888/config/encrypt -H 'Content-Type: application/json' -H 'Accept: application/json' -d 'data here'

read -r -d '' USAGE <<- EOM
This script use GNU sed which is not compatible with MAC OS sed
https://unix.stackexchange.com/questions/13711/differences-between-sed-on-mac-osx-and-other-standard-sed
https://sagebionetworks.jira.com/wiki/spaces/PLFM/pages/21758014/Fixing+sed+on+OSx
if you use MAC OS, install GNU sed first: brew install gnu-sed --with-default-names
SSH forward config server port to local if your are in office network
ssh -L 8818:127.0.0.1:8818 infra-neuroncredit-config

Usage:
encrypt.sh <original_config_file>/<origin_value> <config_server_url>


Example:
./encrypt.sh oracle-staging.env.yml http://localhost:8888/config/encrypt

copy encrypted_value in encrypted file to origin file

curl -u oracle@develop.env:oracle-config_pass http://localhost:8888/config/oracle/develop.env,account-service
EOM

original_config_file="$1"
config_server_url="${2:-http://localhost:8818/config/encrypt}"

encrypt_value(){
    local encrypt_response=$(curl -sSL -X POST ${config_server_url} -H 'Content-Type: application/json' -H 'Accept: application/json' -d $1)
    echo ${encrypt_response}
}

if [ "${original_config_file}" = "-h" ]; then
    echo "${USAGE}"
    exit 0
fi

if [ ! -f "${original_config_file}" ]; then
    echo "encrypt value: ${original_config_file}:"
    encrypt_response=`encrypt_value ${original_config_file}`
    encrypted_value="'{cipher}${encrypt_response}'"
    echo ${encrypted_value}
    exit 0
fi

echo "encrypt file: ${original_config_file}:"
original_config_file_dir=`dirname ${original_config_file}`
original_config_file_name=`basename ${original_config_file}`
encrypted_config_file="${original_config_file_dir}/encrypted_${original_config_file_name}"
cp -f ${original_config_file} ${encrypted_config_file}

## append empty lines to fix sed command problem
echo "" >> ${encrypted_config_file}

IFS=$'\n'
for line in $(cat ${original_config_file} | grep -En '.*((addr).*|(host).*|(jdbc).*|(mail).*|(mongo).*|(name).*|(nodes).*|(pass).*|(port).*|(secret).*|(key).*|(token).*|(uri).*|(url).*|(\-[ ]+.+)$)')
do
    #echo ${line}
    line_number=$(echo ${line} | awk -F: '{print $1}')
    rest_of_line=$(echo ${line} | sed -E 's/^[0-9]+://')
    spaces=$(echo ${rest_of_line} | awk -F'[^ ^\t]' '{print length($1)}')

    key=$(echo ${line} | awk -F: '{print $2}')
    value=$(echo ${line} | sed -E 's/^[0-9]+:[ ]*[^:]*:[ ]*//' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')

    key=$(echo ${key} | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')

    if [[ ${key} == -* ]]; then value="${key}"; key="list_element"; value=$(echo ${value} | sed -E 's/^-[ ]+//'); fi
    if [[ ${key} == \#* ]] || [ -z ${value} ] || [[ ${value} == \{cipher\}* ]]; then continue; fi

    tailing_comment=$(echo ${value} | awk -F'#' '{print $2}')
    if [ ! -z "${tailing_comment}" ]; then value=$(echo ${value} | awk -F'#' '{print $1}' | sed -e 's/[[:space:]]*$//'); fi

    #encrypted_value=${value}
    encrypt_response=`encrypt_value ${value}`
    encrypted_value="{cipher}${encrypt_response}"
    echo "line_number: ${line_number}, spaces: ${spaces}, key: ${key}, value: ${value}, tailing_comment: ${tailing_comment}, encrypted_value: ${encrypted_value}"

    replacement=""
    replacement=$(printf "%-${spaces}s" ${replacement})
    replacement=$(echo ${replacement} | sed 's/ /\\ /g')
    if [ ${key} != "list_element" ]; then
        replacement="${replacement}${key}: '${encrypted_value}'"
    else
        replacement="${replacement}- '${encrypted_value}'"
    fi
    if [ -n "${tailing_comment}" ]; then
        replacement="${replacement} \#${tailing_comment}"
    fi
    replacement="${replacement} \#${value}"
    echo "replacement: ${replacement}"
    sed -i -e "${line_number}d" ${encrypted_config_file}
    sed -i "${line_number}i ${replacement}" ${encrypted_config_file}
done
